function transform(list, parent_group_no = '') {
    let result = [];

    for (let i in list) {
        if (list[i].parent_group_no == parent_group_no) {
            let item = Object.assign({}, list[i]);

            item.children = transform(list, item.group_no);
            result.push(item);
        }
    }

    return result;
}

function transformRev(list) {
    let result = [];

    for (let i in list) {
        let item = list[i];
        let obj = {
            group_no: item.group_no,
            parent_group_no: item.parent_group_no,
            title: item.title,
            create_time: item.create_time || 0
        };

        if (item.new_id) {
            obj.new_id = item.new_id;
        }
        if (item.new_parent_id) {
            obj.new_parent_id = item.new_parent_id;
        }
        result.push(obj);

        if (Array.isArray(item.children) && item.children.length > 0) {
            result = [].concat(result, transformRev(item.children));
        }

    }

    return result;
}

function findAuth(list, group_no) {
    let result = [];

    for (let i = 0, len = list.length; i < len; i++) {
        let item = list[i];

        if (item && (item.group_no == group_no)) {
            result.push(list.splice(i, 1)[0]);
            i--;
        }
    }

    return result;
}

function addAuthToGroup(group, auth, parent_group_no = '') {
    let result = [];
    let left = [];

    for (let i in group) {
        if (group[i].parent_group_no == parent_group_no) {
            let item = Object.assign({}, group[i]);

            item.children = addAuthToGroup(group, auth, item.group_no).resolve;
            let authList = findAuth(auth, item.group_no);

            item.children.push(...authList);
            result.push(item);
        }
    }

    left = [].concat(auth);

    return {
        resolve: result,
        left
    };
}

function extractAuth(list) {
    let result = [];

    for (let i in list) {
        if (Array.isArray(list[i].children) && list[i].children.length > 0) {
            for (let j in list[i].children) {
                if (list[i].children[j].auth_name) {
                    result.push(list[i].children[j]);
                } else {
                    let arr = extractAuth([list[i].children[j]]);

                    result = result.concat(arr);
                }
            }
        }
    }

    return result;
}

function deleteCategory(list, group_no) {
    let arr = [];
    let subList = list.filter(item => item.parent_group_no === group_no);

    subList.forEach(item => {
        arr = deleteCategory(arr, item.group_no);
    });

    return arr.filter(item => item.parent_group_no !== group_no && item.group_no !== group_no);
}

export {
    transform,
    transformRev,
    addAuthToGroup,
    extractAuth,
    deleteCategory
};